//
//  GLPhoneField.swift
//  FanweApp
//
//  Created by zhuxietong on 2019/5/14.
//  Copyright © 2019 xfg. All rights reserved.
//

import Foundation
import Eelay

open class GLPhoneField: JoView,UIStringInput,UITextFieldDelegate{
    open func getStringValue(activeAlert: Bool) -> (ID: String, value: String?, validate: Bool) {
        
        let result = mobileT.getValue(activeAlert: activeAlert)
        let id = result.ID
        let v:String? = self.code + "+" + (result.value ?? "")
        let va = result.validate
        
        return (id,v,va)
    }
    
    
    public required init() {
        super.init()
    }
    
    public required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    required public init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    public var mobileT = JoTextField(id: "mobile", defaultV: "", need: true, hiden: false, rule: JoRule(reg:"\\d{5,15}", nil_msg: "请输入手机号".loc, err_msg: "检查手机号".loc))
    
    public let codeL = UILabel()
    public var code:String = GLCountry.currentCountry["code",""]{
        didSet{
            let _code = "+" + code
            codeL.ui.bfont20.text(color: ._foreground).center.text(_code)
        }
    }
    public let line = UIView()


   open override func addLayoutRules() {
        let selectCodeBt = UIButton()
        eelay = [
            [codeL,[ee.L.Y],.>45.+1000,"20"],
            [selectCodeBt,[codeL,ee.T.L.B.R]],
            [line,[codeL,ee.R,ee.L,6],"12",1,[ee.Y]],
            [mobileT,[codeL,ee.R,ee.L,16],[ee.R],[ee.Y],[ee.T.B]]
        ]
        mobileT.delegate = self
        codeL.setContentConstrainToHighLever()
        line.backgroundColor = UIColor(shex: "#D1D2D9")
        let _code = "+" + code
        codeL.ui.bfont20.text(color: ._foreground).center.text(_code)
//        _ = mobileT.ui.text(color: ._foreground).bfont20.text(text: "18687510604")
        _ = mobileT.ui.text(color: ._foreground).bfont20.text(text: "")

        mobileT.setPlaceholder(info: ("请输入手机号".loc,UIColor(shex:"#D1D2D9"),UIFont.systemFont(ofSize: 15)))
        selectCodeBt.addTarget(self, action: #selector(selectAction), for: .touchUpInside)
        
    }
    
    
    public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    
    public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//        print("+++iiii|\(string)")
        if string == "\n"{
            textField.resignFirstResponder()
            return false
        }
        return true
    }
    
    open func getMobile() -> String? {
        let info = JoPaw.paw(fields: mobileT)
        
        if info.validate{
            let mobile = info.values.mutable_dictionary["mobile",""]
            return code  + "|" + mobile
        }
        return nil
    }
    
    @objc func selectAction(){
        let ctr = GLCountrySelector()
        weak var wself = self
        ctr.selectAction = {
            obj in
            wself?.code = obj["code",""]
        }
//        print("_+++++++|\(mo.controller)")
        mo.controller?.present(ctr, animated: false, completion: nil)
        _ = mobileT.resignFirstResponder()
    }
    
    
    open override func resignFirstResponder() -> Bool{
        super.resignFirstResponder()
        return mobileT.resignFirstResponder()
    }

}


open class GLCountrySelector:GesSideController,ASCollectionVConfig,ASCollectionDelegateFlowLayout{
    
    
    public var ifGlobalSetting:Bool = false
    
    public var code:String = GLCountry.code
    public var collectionNode:ASCollectionNode!
    public var flowLayout = UICollectionViewFlowLayout()
    public var collectionView:UICollectionView{
        get{
            
            return collectionNode.view
        }
    }
    
    public var selectAction:(NSMutableDictionary) ->Void = { _ in }
    
    public func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
        
    }
    required public init() {
        flowLayout = UICollectionViewFlowLayout()
        collectionNode = ASCollectionNode(collectionViewLayout: flowLayout)
        super.init()
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
        
    
    let canleBt = CanleView()
    var sections:TP.section{
        get{
            let sec:TP.section = [
                GLCountry.countrys
            ]
            return sec
        }
    }
    
    var selector:TP.selector = [
        "<default>":Cell.self
    ]
    
    open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        closeBt.ui.nimage(UIImage(named: "gl_close_mark"))
    }
    let closeBt = UIButton()

    open override func viewDidLoad() {
        
//        canleBt.bottomJust = TP.bottomLayoutGuide
//        let tabH = canleBt.bottomJust
//        canleBt.controller = self
        self.side = .bottom(height: (Sheight * 0.5 + 50 +  38))

        super.viewDidLoad()
        flowLayout.sectionHeadersPinToVisibleBounds = true
        flowLayout.minimumLineSpacing = 0
        collectionNode.registerSupplementaryNode(ofKind: UICollectionView.elementKindSectionHeader)

        configCollections(nodes: collectionNode)
        collectionNode.alwaysBounceVertical = true

        gestureAble = false
        
        let titleV = UIView()
        let titleL = UILabel()
        _ = titleL.ui.bfont17.text(color: ._foregroundWeak).center
        titleL.text = "选择地区".loc
        
        let confirmBt = UIButton()
        closeBt.ui.nimage(UIImage(named: "gl_close_mark"))
        confirmBt.ui.nimage(UIImage(named: "gl_select_mark"))

        
        let line = UIView()
        titleV.eelay = [
            [titleL,[ee.Y.X,[-3,0]]],
//            [closeBt,[titleL,ee.Y],[ee.L,20],"16",16],
//            [confirmBt,[titleL,ee.Y],[ee.R,-20],"16",16],
//            [line,[ee.L.B.R],"\(TP.separatorHeight)"]
        ]
        jo_contentView.backgroundColor = ._cellBackground
        line.backgroundColor = UIColor._separator
        
        jo_contentView.eelay = [
            [titleV,[ee.T.L.R],"50"],
            [canleBt,[ee.B,-TP.bottomLayoutGuide],[ee.L.R]],
            [collectionView,[ee.L.R,[14,-14]],[canleBt,ee.T,ee.B],[titleL,ee.B,ee.T,10]],
        ]
        jo_contentView.bsui.set(radius: 16, width: nil, color: nil)
        collectionNode.load(sections: sections, selector: selector)
        collectionView.backgroundColor = ._cellBackground
        collectionNode.reloadData()
        canleBt.bt.addTarget(self, action: #selector(close), for: .touchUpInside)
        closeBt.addTarget(self, action: #selector(close), for: .touchUpInside)
        confirmBt.addTarget(self, action: #selector(confirm), for: .touchUpInside)

    }
    
    @objc func confirm() {
        
    }
    
    
    open func collectionNode(_ collectionNode: ASCollectionNode, nodeForItemAt indexPath: IndexPath) -> ASCellNode {
        
        let cell = collectionNode.cellNode(indexPath: indexPath, fillModel: true, delegate: self)
        cell.neverShowPlaceholders = true
        if let cnode = cell as? JoCellNode
        {
            cnode.delegate = self
        }
   
        return cell
    }
    
    open func collectionNode(_ collectionNode: ASCollectionNode, nodeBlockForItemAt indexPath: IndexPath) -> ASCellNodeBlock {
        return collectionNode.cellBlock(indexPath: indexPath, nodeBuild: ({_ in})).block

    }
    
    @objc public func collectionNode(_ collectionNode: ASCollectionNode, didSelectItemAt indexPath: IndexPath) {
//
//        let list = DataNode.path(node: "section0", collectionNode.model, value: NSMutableArray())
////        list.list { (one:NSMutableDictionary, i) in
////            one[FK.selected] = "NO"
////        }
        if let data = collectionNode.cellData(at: indexPath){
//            data[FK.selected] = "YES"
            data.syncUpdate(value: "0", for: "id")
            if(ifGlobalSetting){
                GLCountry.code = data["code",""]
            }
            self.selectAction(data)
            self.close()
        }
//        collectionNode.reloadData()
        
    }
    
    
    public func collectionView(_ collectionView: ASCollectionView, constrainedSizeForNodeAt indexPath: IndexPath) -> ASSizeRange {
        let size = ASSizeRange.collectionNode(collectionNode: collectionNode, indexPath: indexPath,controller: self)
        return size
    }

    
    
}

extension GLCountrySelector{
    
    public class CanleView: JoView {
//        override var contentHeight: CGFloat{
//            return 38
//        }
        let bt = UIButton()
        public override func addLayoutRules() {
            
            eelay = [
                [bt,[ee.T.L.B.R]],
            ]
            bt.ui.font(size: 14).ncolor(hex: "#999").ntitle(title: "取消".loc)
        }
    }
    
    
    
    
    open class Cell: JoCellNode {
        
        public let nameL = ASTextNode2()
        public let markV = ASImageNode()
        open override func mo_model_reload() {
            mo.model.startSync(scheme: .init(keys: ["id"], primaryKey: "id", table: "GLCountry"))
            mo.model.snycBlock = {[weak self]
                info in
                self?.mo_model_reload()
            }
            separatorHeight = TP.separatorHeight
            separatorColor = ._separator
            nameL.attributedText = "(+\(mo.model["code",""])) ".ui.bfont13.color(color: ._foreground).astring + mo.model["name",""].loc.ui.font14.color(color: ._foregroundWeak).astring
            
            var select_code = GLCountry.code
            if let ctr = mo.controller as? GLCountrySelector{
                select_code = ctr.code
            }
            if mo.model["code",""] == select_code
            {
                markV.image = UIImage(named: "gl_select_mark")
            }
            else{
                markV.image = nil
            }
            
        }
        
        open override func specGetter() -> _Spec {
            return .stack(["h|10",[18,20],&-.center,_justfy(.space_between)], childs: [
            nameL.Spec,
            markV["16",16]
            ])
        }
    }
}
